﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
void ErrorHandle(const char *message);
#define BUF_SIZE 1024
int main(int args, char *argv[])
{

  // step01:创建套接字
  int sock_clnt;
  sock_clnt = socket(PF_INET, SOCK_STREAM, 0);
  if (sock_clnt == -1)
    ErrorHandle("socket() error!");
  // step02:请求连接
  struct sockaddr_in addr_serv{};
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(argv[1]);
  addr_serv.sin_port = htons(atoi(argv[2]));
  auto connect_result = connect(sock_clnt, (sockaddr *)&addr_serv, sizeof(addr_serv));
  if (connect_result == -1)
    ErrorHandle("connect() error!");
  else
    std::cout << "connect() ok ..." << std::endl;

  char message[BUF_SIZE];
  char response[BUF_SIZE];
  while (1)
  {
    std::cout << "Input message(Q to quit):";
    fgets(message, BUF_SIZE, stdin);
    if (strcmp(message,"q\n")==0 || strcmp(message,"Q\n")== 0)
      break;
    write(sock_clnt, message, sizeof(message));
    auto strlen = read(sock_clnt, response, BUF_SIZE - 1);
    std::cout << "Message from server:" << response << std::endl;
  }
  close(sock_clnt);
  return 0;
}
void ErrorHandle(const char *message)
{
  std::cout << message << std::endl;
  exit(-1);
}